<script setup>
import { useRouter } from 'vue-router';
import { ref } from 'vue'
import { changeInfoFn } from '@/api/user';
import { useUserStore } from '@/stores/user';
import { showToast } from 'vant';

const user = useUserStore()
const router = useRouter()
const username = ref('')
const fileList = ref([])
const flag = ref(true)
const imgurl = ref('')

function tomy() {
    router.back()
}

function changeMethod() {
    flag.value = !flag.value
}

function onSubmit() {
    let img = ''
    if (flag.value) {
        if (fileList.value.length > 0) {
            img = fileList.value[0].content
        }
    } else {
        img = imgurl.value
    }

    changeInfoFn({
        userid: user.userInfo.userid,
        username: username.value,
        img
    }).then(res => {
        // console.log(res);
        showToast(res.message)
        router.push('/my')
    })
}

</script>

<template>
    <div class="main">
        <van-nav-bar title="我的信息" left-text="返回" left-arrow @click-left="tomy" />
        <div class="content">
            <van-button @click="changeMethod">{{ flag ? '图片URL' : '本地图片' }}</van-button>
            <van-form @submit="onSubmit">
                <van-cell-group inset>
                    <van-field v-model="username" name="新用户名" label="新用户名" placeholder="请输入10位新用户名" />
                </van-cell-group>
                <van-uploader v-if="flag" v-model="fileList" max-count='1' />
                <van-cell-group v-else inset>
                    <van-field v-model="imgurl" name="图片URL" label="图片URL" placeholder="请输入图片URL" />
                </van-cell-group>
                <div style="margin: 16px;">
                    <van-button class="button" round block type="danger" native-type="submit"
                        :disabled="username.length > 10">
                        确定修改
                    </van-button>
                </div>
            </van-form>
        </div>
    </div>
</template>
<style lang="scss" scoped>
.content {
    margin-top: 10px;
    position: relative;

    .van-button--block {
        width: 80%;
        position: absolute;
        top: 200px;
        left: 37.5px;
    }
}
</style>